package com.demo;

/**
 * @Author 56465
 * @Create 2024/7/30 9:33
 */
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;

public class H1InsertionExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField textField = new TextField();

        // 监听文本框中的键入事件
        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCharacter().equals("#")) {
                    int caretPosition = textField.getCaretPosition();


                    // 插入 "<h1>" 在 # 前面
                    String textBefore = textField.getText(0, caretPosition - 1);
                    String textAfter = textField.getText(caretPosition, textField.getLength());
                    textField.setText(textBefore + "<h1>" + "#" + "</h1>" + textAfter);

                    // 设置光标位置到 # 后面
                    textField.positionCaret(caretPosition + 5); // 跳过 "<h1>"
                }
            }
        });

        VBox root = new VBox(textField);
        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("H1 Insertion Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
